package au.edu.utas.yu_qiao_group.luckyman.ui.recordlist;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.core.content.FileProvider;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import au.edu.utas.yu_qiao_group.luckyman.MainActivity;
import au.edu.utas.yu_qiao_group.luckyman.R;
import au.edu.utas.yu_qiao_group.luckyman.databinding.FragmentRecordListBinding;
import au.edu.utas.yu_qiao_group.luckyman.db.draws.DrawDTO;
import au.edu.utas.yu_qiao_group.luckyman.db.raffles.RaffleDTO;
import au.edu.utas.yu_qiao_group.luckyman.db.raffles.RaffleDrawDTO;
import au.edu.utas.yu_qiao_group.luckyman.db.tickets.TicketDTO;
import au.edu.utas.yu_qiao_group.luckyman.service.RaffleService;
import au.edu.utas.yu_qiao_group.luckyman.service.TicketService;
import au.edu.utas.yu_qiao_group.luckyman.ui.components.ArrayAdapterSearchView;
import au.edu.utas.yu_qiao_group.luckyman.ui.components.SwipeRecyclerView;
import au.edu.utas.yu_qiao_group.luckyman.utils.FormatUtils;

import static au.edu.utas.yu_qiao_group.luckyman.ui.recordlist.ShareManager.bitMap2File;

public class RecordListFragment extends Fragment {

  private static final String TAG = "RecordList";
  private ArrayList<RaffleDTO> mRaffleList = null;
  private RaffleDrawDTO targetRaffle = null;

  private CardView mRaffleItem;
  private FragmentRecordListBinding mBinding;
  private SwipeRecyclerView mRecyclerView;
  private ArrayAdapterSearchView mSearchView;

  private SwipeRecyclerView.Adapter mAdapter;
  private List<TicketDTO> mDataSet;
  protected SwipeRecyclerView.LayoutManager mLayoutManager;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initSearchData();
//        mTargetRaffleVm = new ViewModelProvider(getActivity()).get(SharedRaffleViewModel.class);
  }

  public View onCreateView(@NonNull LayoutInflater inflater,
                           ViewGroup container, Bundle savedInstanceState) {
//    View rootView = inflater.inflate(R.layout.fragment_record_list, container, false);


    mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.fragment_record_list, container, false);
    View rootView = mBinding.getRoot();
    rootView.setTag(TAG);
    initRecyclerView(rootView);
    initRaffleItem(rootView);

    mSearchView = (ArrayAdapterSearchView) rootView.findViewById(R.id.record_search_bar);
    mSearchView.setIconifiedByDefault(false);
    setSearchView(rootView);
    return rootView;
  }

  public void setSearchView(View rootView) {
    MainActivity activity = (MainActivity) getActivity();
    RaffleListAdapter adapter = new RaffleListAdapter(getContext(), mRaffleList);
    mSearchView.setAdapter(adapter);
    mSearchView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        RaffleDTO r = (RaffleDTO) parent.getItemAtPosition(position);
        targetRaffle = RaffleService.retreiveRaffleDrawByID(activity.mDb, r.getMRaffleID());
        if (targetRaffle != null) {
          mBinding.setRaffle(targetRaffle);
          mRaffleItem.setVisibility(View.VISIBLE);
          mSearchView.setText(targetRaffle.getMName());
          updateRecordList();
        }
      }
    });
  }

  public void fireSharingIntent(View view) {
    Bitmap compressdImage = ShareManager.compressImage(ShareManager.getBitmapByView(view));
    File filepath = getContext().getExternalFilesDir("my_temp");
    File file = ShareManager.bitMap2File(filepath, compressdImage);
    if (file != null && file.exists() && file.isFile()) {
      Context context = getContext();
      Uri imageUri = FileProvider.getUriForFile(
              context,
              context.getPackageName() + ".fileprovider",
              file);
      String messageContent = "Check this raffle: "+targetRaffle.getMName()+"\n only "
              + FormatUtils.formatCurrency(targetRaffle.getMUnitPrice())
              + " to have a chance to get " + FormatUtils.formatCurrency(targetRaffle.getMAwardPrice())
              + "!!!\n Drawing on " + FormatUtils.dateToString(targetRaffle.getMDrawTime());
      Intent shareIntent = new Intent();
      shareIntent.setAction(Intent.ACTION_SEND);
      shareIntent.putExtra(Intent.EXTRA_TEXT, messageContent);
      shareIntent.putExtra(Intent.EXTRA_STREAM, imageUri);
      shareIntent.setType("image/*");
      startActivity(Intent.createChooser(shareIntent, "sharing raffle"));
    }
  }

  private void updateRecordList() {
    MainActivity activity = (MainActivity) getActivity();
    mDataSet = TicketService.retrieveAllByRaffleID(activity.mDb, targetRaffle.getMRaffleID());
    targetRaffle.setMTotalIncome(mDataSet.stream().map(i -> i.getMPurchasePrice()).reduce(0, Integer::sum));
    RecordListViewItemAdapter adapter = new RecordListViewItemAdapter(mDataSet, mOnEditBtnClick, mOnDelBtnClick);
    mRecyclerView.setAdapter(adapter);
  }

  private View.OnClickListener mOnEditBtnClick = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      if (targetRaffle.getMDrawStatus() == DrawDTO.STATUS_FINISHED) {
        Toast.makeText(getContext(), "Cannot commit edit because the draw is COMPLETED!", Toast.LENGTH_SHORT).show();
        return;
      }
      final EditText edit = new EditText(getContext());
      TicketDTO t = mDataSet.get((Integer) v.getTag());
      edit.setText(t.getMCustomerPhone());
      AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
      dialog.setTitle("Please edit customer phone");
      dialog.setView(edit);
      dialog.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
          String newPhone = edit.getText().toString();
          if (TextUtils.isEmpty(newPhone) || newPhone.length() != 10) {
            Toast.makeText(getContext(), "Customer phone length should be 10", Toast.LENGTH_SHORT).show();
            return;
          }
          t.setMCustomerPhone(newPhone);
          MainActivity activity = (MainActivity) getActivity();
          try {
            TicketService.updateTicket(activity.mDb, t);
            Toast.makeText(getContext(), "Edit success!", Toast.LENGTH_SHORT).show();
            updateRecordList();
            dialog.dismiss();
          } catch (Exception e) {
            Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
          }
        }
      });
      dialog.show();
    }
  };

  private View.OnClickListener mOnDelBtnClick = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      if (targetRaffle.getMDrawStatus() == DrawDTO.STATUS_FINISHED) {
        Toast.makeText(getContext(), "Cannot commit refund because the draw is COMPLETED!", Toast.LENGTH_SHORT).show();
        return;
      }
      AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
      dialog.setMessage("please double confirm your dangerous DELETE action");
      dialog.setPositiveButton("I am sure", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
          TicketDTO targetDTO = mDataSet.get((Integer) v.getTag());
          MainActivity activity = (MainActivity) getActivity();
          if (TicketService.delTicket(activity.mDb, targetDTO, targetRaffle)) {
            Toast.makeText(getContext(), "refund successfully ", Toast.LENGTH_SHORT).show();
            updateRecordList();
          } else {
            Toast.makeText(getContext(), "delete failed!", Toast.LENGTH_SHORT).show();
          }
        }
      });
      dialog.show();
    }
  };

  private void initSearchData() {
    MainActivity activity = (MainActivity) getActivity();
    mRaffleList = RaffleService.retrieveAll(activity.mDb);
  }

  private void initRaffleItem(final View rootView) {
    mRaffleItem = rootView.findViewById(R.id.raffle_item);
    mRaffleItem.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        fireSharingIntent(mRaffleItem);
      }
    });
  }

  private void initRecyclerView(final View rootView) {
    mRecyclerView = rootView.findViewById(R.id.ticket_list);
    mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.scrollToPosition(0);
  }
}
